package com.cmc.cloud.cmclink.doc.service.impl.manifest;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.ManifestCargoErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.convert.ManifestCargoCntrConvert;
import com.cmc.cloud.cmclink.doc.convert.ManifestCargoConvert;
import com.cmc.cloud.cmclink.doc.entity.ManifestCargoCntrDO;
import com.cmc.cloud.cmclink.doc.entity.ManifestCargoDO;
import com.cmc.cloud.cmclink.doc.mapper.ManifestCargoCntrMapper;
import com.cmc.cloud.cmclink.doc.mapper.ManifestCargoMapper;
import com.cmc.cloud.cmclink.doc.mapper.ManifestCntrMapper;
import com.cmc.cloud.cmclink.doc.service.manifest.ManifestCargoService;
import com.cmc.cloud.cmclink.doc.api.document.rep.manifestrep.manifestcargo.ManifestCargoCreateReqVO;
import com.cmc.cloud.cmclink.doc.api.document.rep.manifestrep.manifestcargo.ManifestCargoRespVO;
import com.cmc.cloud.cmclink.doc.api.document.rep.manifestrep.manifestcargo.ManifestCargoUpdateReqVO;
import com.cmes.framework.common.exception.util.ServiceExceptionUtil;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 舱单货物信息 Service 实现类
 *
 * @author chenzheng
 */
@Service
@Validated
public class ManifestCargoServiceImpl implements ManifestCargoService {

    @Resource
    private ManifestCargoMapper manifestCargoMapper;

    @Resource
    private ManifestCntrMapper manifestCntrMapper;

    @Resource
    private ManifestCargoCntrMapper manifestCargoCntrMapper;


    @Override
    public void createManifestCargo(ManifestCargoCreateReqVO createReqVO) {
        // 插入
        ManifestCargoDO manifestCargo = ManifestCargoConvert.INSTANCE.convert(createReqVO);
        manifestCargoMapper.insert(manifestCargo);
    }

    @Override
    public void updateManifestCargo(ManifestCargoUpdateReqVO updateReqVO) {
        // 校验存在
        validateManifestCargoExists(updateReqVO.getId());
        // 更新
        ManifestCargoDO updateObj = ManifestCargoConvert.INSTANCE.convert(updateReqVO);
        manifestCargoMapper.updateById(updateObj);
    }

    @Override
    public void deleteManifestCargo(Long id) {
        // 校验存在
        validateManifestCargoExists(id);
        // 删除
        manifestCargoMapper.deleteById(id);
    }

    private void validateManifestCargoExists(Long id) {
        if (manifestCargoMapper.selectById(id) == null) {
            throw ServiceExceptionUtil.exception(ManifestCargoErrorCodeConstants.MANIFEST_CARGO_NOT_EXISTS);
        }
    }

    @Override
    public ManifestCargoDO getManifestCargo(Long id) {
        return manifestCargoMapper.selectById(id);
    }

    @Override
    public List<ManifestCargoDO> getManifestCargoList(Collection<Long> ids) {
        return manifestCargoMapper.selectBatchIds(ids);
    }

    @Override
    public void createOrUpdateAndDeleteBatch(Long manifestId, List<ManifestCargoUpdateReqVO> newList, List<ManifestCargoRespVO> oldList) {
        // 无效数据直接返回
        if (CollectionUtil.isEmpty(newList) && CollectionUtil.isEmpty(oldList)) {
            return;
        }
        // 默认值
        if (CollectionUtil.isEmpty(newList)) {
            newList = new ArrayList<>();
        }
        if (CollectionUtil.isEmpty(oldList)) {
            oldList = new ArrayList<>();
        }
        List<ManifestCargoUpdateReqVO> createList = new ArrayList<>();
        List<ManifestCargoUpdateReqVO> updateList = new ArrayList<>();
        // 历史数据
        Set<Long> oldIds = oldList.stream().map(e -> e.getId()).collect(Collectors.toSet());
        newList.forEach(e -> {
            if (e.getId() != null) {
                if (oldIds.contains(e.getId())) {
                    // 正常更新
                    updateList.add(e);
                    oldIds.remove(e.getId()); // 剩下的数据需要删除
                } else {
                        // 数据更新非法
                        throw ServiceExceptionUtil.exception(ManifestCargoErrorCodeConstants.MANIFEST_CARGO_NOT_EXISTS);
                }
            } else {
                e.setManifestId(manifestId);
                createList.add(e);
            }
        });
        if (CollectionUtil.isNotEmpty(oldIds)) {
            // 没有匹配上的就是前端删除的
            manifestCargoMapper.deleteBatchIds(oldIds);
            deleteCargoCntrByCargoIds(oldIds);
        }
        if (CollectionUtil.isNotEmpty(createList)) {
            List<ManifestCargoDO> manifestCargoCreateList = ManifestCargoConvert.INSTANCE.convertUpdateList(createList);
            manifestCargoMapper.insertBatch(manifestCargoCreateList);
            addCargoCntr(manifestCargoCreateList, createList);
        }
        if (CollectionUtil.isNotEmpty(updateList)) {
            List<ManifestCargoDO> manifestCargoUpdateList = ManifestCargoConvert.INSTANCE.convertUpdateList(updateList);
            manifestCargoMapper.updateBatch(manifestCargoUpdateList);
            deleteCargoCntrByCargoIds(manifestCargoUpdateList.stream().map(e -> e.getId()).collect(Collectors.toSet()));
            addCargoCntr(manifestCargoUpdateList, updateList);
        }
    }

    public void deleteCargoCntrByCargoIds(Set<Long> cargoIds) {
        LambdaUpdateWrapper<ManifestCargoCntrDO> queryWrapperX = new LambdaUpdateWrapper<ManifestCargoCntrDO>();
        queryWrapperX.in(ManifestCargoCntrDO::getCargoId, cargoIds);
        manifestCargoCntrMapper.delete(queryWrapperX);
    }

    public void addCargoCntr(List<ManifestCargoDO> manifestCargoList, List<ManifestCargoUpdateReqVO> newList) {
        List<ManifestCargoCntrDO> cargoCntrAllList = new ArrayList<>(16);
        for (int i = 0; i < newList.size(); i++) {
            ManifestCargoDO manifestCargo = manifestCargoList.get(i);
            ManifestCargoUpdateReqVO createTemp = newList.get(i);
            if (CollectionUtil.isNotEmpty(createTemp.getCntrNoList())) {
                List<ManifestCargoCntrDO> cargoCntrList = ManifestCargoCntrConvert.INSTANCE.convertUpdateList(createTemp.getCntrNoList());
                cargoCntrList.forEach(e -> {
                    e.setId(null);
                    e.setCargoId(manifestCargo.getId());
                });
                cargoCntrAllList.addAll(cargoCntrList);
            }
        }
        if (CollectionUtil.isNotEmpty(cargoCntrAllList)) {
            manifestCargoCntrMapper.insertBatch(cargoCntrAllList);
        }
    }

    @Override
    public void addCargoCntrResp(List<ManifestCargoDO> manifestCargoList, List<ManifestCargoRespVO> newList) {
        List<ManifestCargoCntrDO> cargoCntrAllList = new ArrayList<>(16);
        for (int i = 0; i < newList.size(); i++) {
            ManifestCargoDO manifestCargo = manifestCargoList.get(i);
            ManifestCargoRespVO createTemp = newList.get(i);
            if (CollectionUtil.isNotEmpty(createTemp.getCntrNoList())) {
                List<ManifestCargoCntrDO> cargoCntrList = ManifestCargoCntrConvert.INSTANCE.convertRespList(createTemp.getCntrNoList());
                cargoCntrList.forEach(e -> {
                    e.setId(null);
                    e.setCargoId(manifestCargo.getId());
                });
                cargoCntrAllList.addAll(cargoCntrList);
            }
        }
        if (CollectionUtil.isNotEmpty(cargoCntrAllList)) {
            manifestCargoCntrMapper.insertBatch(cargoCntrAllList);
        }
    }
}
